import { message } from "@/utils/message";

/**
 * 时间格式化处理
 * @param {Object} now 时间
 * @param {Object} mask 格式 例如"yyyy-MM-dd HH:mm"
 */
function getFormatDate(now: any, mask: string) {
  const d = now;
  const zeroize = function (value, length) {
    if (!length) length = 2;
    value = String(value);
    let zeros = "";
    for (let i = 0; i < length - value.length; i++) {
      zeros += "0";
    }
    return zeros + value;
  };
  return mask.replace(
    /"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g,
    function ($0) {
      switch ($0) {
        case "d":
          return d.getDate();
        case "dd":
          //@ts-ignore
          return zeroize(d.getDate());
        case "ddd":
          return ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"][d.getDay()];
        case "dddd":
          return [
            "Sunday",
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"
          ][d.getDay()];
        case "M":
          return d.getMonth() + 1;
        case "MM":
          //@ts-ignore
          return zeroize(d.getMonth() + 1);
        case "MMM":
          return [
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "Jun",
            "Jul",
            "Aug",
            "Sep",
            "Oct",
            "Nov",
            "Dec"
          ][d.getMonth()];
        case "MMMM":
          return [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
          ][d.getMonth()];
        case "yy":
          return String(d.getFullYear()).substr(2);
        case "yyyy":
          return d.getFullYear();
        case "h":
          return d.getHours() % 12 || 12;
        case "hh":
          //@ts-ignore
          return zeroize(d.getHours() % 12 || 12);
        case "H":
          return d.getHours();
        case "HH":
          //@ts-ignore
          return zeroize(d.getHours());
        case "m":
          return d.getMinutes();
        case "mm":
          //@ts-ignore
          return zeroize(d.getMinutes());
        case "s":
          return d.getSeconds();
        case "ss":
          //@ts-ignore
          return zeroize(d.getSeconds());
        case "l":
          return zeroize(d.getMilliseconds(), 3);
        case "L":
          let m = d.getMilliseconds();
          if (m > 99) m = Math.round(m / 10);
          //@ts-ignore
          return zeroize(m);
        case "tt":
          return d.getHours() < 12 ? "am" : "pm";
        case "TT":
          return d.getHours() < 12 ? "AM" : "PM";
        case "Z":
          return d.toUTCString().match(/[A-Z]+$/);
        default:
          return $0.substr(1, $0.length - 2);
      }
    }
  );
}

/**
 * 字符格式化处理 处理的格式为=> stringFormat("{0}"你好,"中国")
 * @param first 第一文本内容
 * @param theArgs 剩余参数
 * @return {*} 返回正常格式字符
 */
function stringFormat(first: string, ...theArgs) {
  let str = first;
  for (let i = 0; i < theArgs.length; i++) {
    const re = new RegExp("\\{" + i + "\\}", "gm");
    str = str.replace(re, theArgs[i]);
  }
  return str;
}

/*
 *   功能:实现VBScript的DateAdd功能.
 *   参数:interval,字符串表达式，表示要添加的时间间隔.
 *   参数:number,数值表达式，表示要添加的时间间隔的个数.
 *   参数:date,时间对象.
 *   返回:新的时间对象.
 *   let now = new Date();
 *   let newDate = DateAdd( "d", 5, now);
 *---------------   DateAdd(interval,number,date)   -----------------
 */
function dateAdd(interval, number, date) {
  switch (interval) {
    case "y":
      date.setFullYear(date.getFullYear() + number);
      break;
    case "q":
      date.setMonth(date.getMonth() + number * 3);
      break;
    case "M":
      date.setMonth(date.getMonth() + number);
      break;
    case "w":
      date.setDate(date.getDate() + number * 7);
      break;
    case "d":
      date.setDate(date.getDate() + number);
      break;
    case "h":
      date.setHours(date.getHours() + number);
      break;
    case "m":
      date.setMinutes(date.getMinutes() + number);
      break;
    case "s":
      date.setSeconds(date.getSeconds() + number);
      break;
    default:
      date.setDate(date.getDate() + number);
      break;
  }
  return date;
}

function platform() {
  const u = navigator.userAgent;
  //@ts-ignore
  if (typeof xapp != "undefined") {
    if (u.indexOf("Android") > -1 || u.indexOf("Adr") > -1) {
      return "android";
    } else if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      return "ios";
    } else {
      return "native";
    }
  } else if (u.indexOf("Android") > -1 || u.indexOf("Adr") > -1) {
    return "h5_android";
  } else if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return "h5_ios";
  } else {
    return "web";
  }
}

function generateUniqueID() {
  // 获取当前时间的时间戳
  const timestamp = Date.now().toString();
  // 生成一个随机数，确保可以组成8位数
  const randomNumber = Math.floor(10000000 + Math.random() * 90000000);
  // 将时间戳和随机数拼接成一个字符串，然后截取前8位
  return (
    timestamp.substr(0, 8 - randomNumber.toString().length) +
    randomNumber.toString()
  );
}

/**
 * 将对应的秒数转成时间格式 HH:mm
 * @param seconds 秒数总和
 */
function convertSecondsToHHMM(seconds: any) {
  const hours = Math.floor(seconds / 3600); // 计算小时数
  const minutes = Math.floor((seconds % 3600) / 60); // 计算剩余的分钟数
  let hoursTxt = hours.toString();
  if (hours < 10) {
    hoursTxt = "0" + hoursTxt;
  }
  let minutesTxt = minutes.toString();
  if (minutes < 10) {
    minutesTxt = "0" + minutesTxt;
  }
  return hoursTxt + ":" + minutesTxt;
}

/**
 * 复制文本
 * @param text 待复制文本
 */
function copyText(text: string) {
  const createInput = document.createElement("textarea");
  createInput.value = text;
  document.body.appendChild(createInput);
  createInput.select();
  document.execCommand("Copy");
  createInput.className = "createInput";
  createInput.style.display = "none";
  message("复制成功", { type: "success" });
}

/**
 * 嵌套的多级数据结构拆分为一维数组
 * @param data 返回一级数据
 */
function flattenData(data) {
  const result = [];
  function traverse(node) {
    if (node) {
      result.push(node); // 将当前节点加入结果数组
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          traverse(child); // 递归处理子节点
        });
      }
    }
  }
  traverse(data); // 从根节点开始递归
  return result;
}

export {
  dateAdd,
  copyText,
  stringFormat,
  getFormatDate,
  generateUniqueID,
  platform,
  convertSecondsToHHMM,
  flattenData
};
